package com.wiz.netty.task;

import java.util.Iterator;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerContext;
import org.quartz.SchedulerException;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.google.common.collect.Multimap;
import com.wiz.log.NettyInfoRecord;
import com.wiz.web.manager.ServiceManager;
import com.wiz.web.vo.TransmissionTaskVO;

public class NettyTransmissionTask extends QuartzJobBean{
//	private transient final Logger log = LoggerFactory.getLogger(getClass());
	
	private ServiceManager serviceManager;
	

	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
//		Scheduler scheduler = (Scheduler) context.getScheduler(); 
		if(serviceManager == null){
			SchedulerContext schCtx;
			try {
				schCtx = context.getScheduler().getContext();
				//获取Spring中的上下文    
				ApplicationContext appCtx = (ApplicationContext)schCtx.get("applicationContext");  
				serviceManager = (ServiceManager) appCtx.getBean("serviceManager");
			} catch (SchedulerException e) {
				e.printStackTrace();
			}
		}
		Multimap<String, TransmissionTaskVO> map = serviceManager.getTransmissionTaskMap();
    	Iterator it = map.keySet().iterator();
    	long nowTime = System.currentTimeMillis();
    	int count = 0;
    	while(it.hasNext()){
    		String stationId = (String) it.next();
    		if(serviceManager.getStationConnectMap().containsKey(stationId)){//连接在线执行任务
	    		Iterator vit = map.get(stationId).iterator();
	    		while(vit.hasNext()){
	    			TransmissionTaskVO vo = (TransmissionTaskVO) vit.next();
	    			if(nowTime - vo.getStartTime() >= vo.getIntervalTime()){//大于间隔时间才会发送
	    				count++;
    					NettyInfoRecord.infoRecord("NettyTransmissionTask send "+vo.getMessage().getMab().toStringUtf8()+" to "+stationId);
    					serviceManager.getStationConnectMap().get(stationId).writeAndFlush(vo.getMessage());
	    			}
	    		}
    		}//即使连接不在线也不会删除任务，后期可能改动
    	}
    	NettyInfoRecord.infoRecord(count+" task is excuted..................");
	}
}
